package com.kakavr.auth.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;

import com.kakavr.util.SessionUtils;

public class AuthenInterceptor extends AbstractHandlerInterceptor {
	/**
	 * 执行方法之前执行该操作
	 */
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 检查请求来源
		/*if (isAjaxRequest(request)) {
			String referer = request.getHeader("Referer");
			if (!chechReferer(referer)) {
				wrapResult(MsgConstants.MSG_CODE_SOURCE,
						MsgConstants.MSG_SOURCE_ILLEGAL, response);
				return false;
			}
		}*/
		// 检查是否已认证
		String targetURL = getTargetURL(request);
		if (!isOpenUrl(targetURL)) {
			HttpSession session = SessionUtils.getSession(true);
			// 是否登陆
			boolean flag = isAuthen(session);
			if (!flag) {
				noAuthen(request, response);
				return false;
			}
		}
		return true;
	}

	/**
	 * This implementation is empty.
	 */
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 处理完之后执行
	 */
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
}
